package com.panopset.sf;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import com.panopset.compat.Strings;

public abstract class PanField {

	protected final Windoc sd;
	protected final String title;
	protected final String dft;

	public PanField(final Windoc swingDoc, final String borderTitle,
			final String defaultValue) {
		title = borderTitle;
		dft = defaultValue;
		sd = swingDoc;
	}

	/**
	 * As part of creating this panel, make sure you add the JComponent returned
	 * by getTF().
	 * 
	 * @param p
	 *            Panel to populate.
	 */
	protected abstract void populatePanel(JPanel panel);

	private JPanel panel;

	public JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			TitledBorder tb = new TitledBorder(title);
			FontManager.getInstance().register(tb,
					FontManager.FontType.borderTitle);
			panel.setBorder(tb);
			populatePanel(panel);
		}
		return panel;
	}

	public Windoc getDoc() {
		return sd;
	}

	private JTextField tf;

	protected JTextField getTF() {
		if (tf == null) {
			tf = new JTextField();
			FontManager.getInstance().register(tf,
					FontManager.FontType.monospace);
			String s = sd.getFileProps().get(title);
			if (Strings.isPopulated(s)) {
				tf.setText(s);
			} else {
				tf.setText(dft);
			}
			tf.addFocusListener(new FocusListener() {

				@Override
				public void focusGained(FocusEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void focusLost(FocusEvent e) {
					sd.getFileProps().put(title,
							((JTextField) e.getSource()).getText());
				}

			});
		}
		return tf;
	}
}
